/**
 * @params  {String}    targetUrl: 'http://10.1.40.152:8082'
 * @params  {[Number]}    localPort: 8080
 *
 */

function webProxy(targetUrl, localPort,prefix) {
    const http = require('http'),
        httpProxy = require('http-proxy'),
        fs = require('fs'),
        url = require('url'),
        path = require('path'),
        localport = localPort || 8080;
        prefix = prefix || 'webapi'

    let proxy = httpProxy.createProxyServer({
        target: targetUrl,
        secure: false
    })

    proxy.on('error', function (err, request, response) {
        res.writeHead(500, {
            'Content-Type': 'text/plain'
        })
        console.log(err)
        res.end('Something went wrong.')
    })


    let server = http.createServer((request, response) => {
        if (request.path !== "/") {
            response.setHeader("Access-Control-Allow-Credentials", true);
            // 这里获取 origin 请求头 而不是用 *
            response.setHeader("Access-Control-Allow-Origin", request.headers["origin"] || "*");
            response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");
            response.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
            response.setHeader("Content-Type", "application/json;charset=utf-8");
        }
        let pathName = url.parse(request.url).pathname,
            realPath = request.url.substring(1),
            extName = realPath,
            indexOfQuestionMark = extName.indexOf('?');

        if (indexOfQuestionMark >= 0) {
            extName = extName.substring(0, indexOfQuestionMark);
            realPath = realPath.substring(0, indexOfQuestionMark);
        }

        extName = path.extname(extName);
        extName = extName ? extName.slice(1) : 'unknown';
        var re = new RegExp("\/"+prefix+"\/.*$");
        if (re.test(pathName)) {
            proxy.web(request, response);
            return;
        }

        if (!fs.existsSync(realPath)) {
            response.writeHead(404, {
                'content-type': 'text/plain'
            });
            response.write('The request URL:' + realPath + ' could not be found.');
            response.end();
            return;
        }

    });

    console.log('listening on port ' + localport)

    server.listen(localport);
}

module.exports.webProxy = webProxy;